package com.joysuch.wwyt.api.mh.socket;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.Charset;


@Slf4j
public class MhWebSocketClient {

    private Socket socket;
    private OutputStream os;
    private InputStream is;

    public MhWebSocketClient(String sendIp, Integer sendPort) {
        try {
            this.socket = new Socket();
            this.socket.connect(new InetSocketAddress(sendIp, sendPort), 5000);
            this.socket.setSoTimeout(5000);
            this.os = this.socket.getOutputStream();
            this.is = this.socket.getInputStream();
        } catch (IOException e) {
            log.error("init socket exception", e);
        }
    }

    public boolean isOpen() {
        return !this.socket.isClosed();
    }

    public void close() {
        try {
            this.socket.close();
        } catch (IOException e) {
            log.error("close socket exception", e);
        }
    }

    public boolean send(String text) {
        try {
            this.os.write(text.getBytes(Charset.forName("UTF-8")));
            byte[] bs = new byte[1024];
            try {
                int read = this.is.read(bs);
                byte[] r = new byte[read];
                System.arraycopy(bs, 0, r, 0, read);
                log.info("get return msg {}", new String(r));
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("... socket send out message : {}", text);
            return true;
        } catch (Exception e) {
            log.error("write data exception", e);
            try {
                this.socket.close();
            } catch (IOException ignore) {
                log.error("socket close error: ", ignore);

            }
            return false;
        }

    }

}
